export default class Query {
    static options={
        host:'',
        type:'json',
        callback() {},
    }
    constructor(type, url, data, options = {}) {
        this.type = type;
        this.url =Query.options.host + url
        this.data = this.format(data);
        this.options = Object.assign(
            Query.options,options
        );
        this.xhr = new XMLHttpRequest();
    }

    static config(options) {
        Query.options=options
    }

    format(data) {
        let form=new FormData();
        for (const [k,v] of Object.entries(data)) {
            form.append(k,v);
        }
        return form
    }

    static get(url, options) {
        return new Query('get', url, {}, options).send();
    }

    static post(url, data, options) {
        return new Query('post', url,data,options).send()
    }

    send() {
        return new Promise((resolve, reject) => {
            this.xhr.open(this.type, this.url);
            this.xhr.responseType = this.options.type;
            this.xhr.send(this.data);
            this.xhr.onload = () => {
            if (this.xhr.status == 200) {
                resolve(this.xhr.response);
            }
            else {
                reject(this.xhr.responsetext)
            }
        };
        })
    }
}
